package org.example.day20240909.dao;

import org.example.day20240909.model.Employee;
import org.example.day20240909.util.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class EmployeeDao {
    String STATE_ON = "有效数据";
    String De_STATE_ON = "有效";
    String DELETE_ON = "已删除";

    public List<Employee> checkEmployeeList() {
        Connection connection = JDBCUtils.getConnection();
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            String employeeSql = "select * from employee";
            ps = connection.prepareStatement(employeeSql);
            rs = ps.executeQuery();
            List<Employee> employeeList = new ArrayList<>();
            while (rs.next()) {
                Employee employeeReturn = new Employee();
                employeeReturn.setEmployee_id(rs.getString("employee_id"));
                employeeReturn.setEmployee_name(rs.getString("employee_name"));
                employeeReturn.setEmployee_email(rs.getString("employee_email"));
                employeeReturn.setBirthday(rs.getString("birthday"));
                employeeReturn.setAge(rs.getDouble("age"));
                employeeReturn.setJoin_date(rs.getString("join_date"));
                employeeReturn.setWork_experience(rs.getDouble("work_experience"));
                employeeReturn.setHire_date(rs.getString("hire_date"));
                employeeReturn.setCompany_experience(rs.getDouble("company_experience"));
                employeeReturn.setGender(rs.getString("gender"));
                employeeReturn.setDepartment_name(rs.getString("department_name"));
                employeeReturn.setState(rs.getString("state"));
                employeeList.add(employeeReturn);
            }
            return employeeList;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                rs.close();
                ps.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public boolean checkEmployeeId(String inputId) {
        Connection connection = JDBCUtils.getConnection();
        String employeeSql = "select count(*) as cnt from employee where employee_id = ?";
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            ps = connection.prepareStatement(employeeSql);
            ps.setString(1, inputId);
            rs = ps.executeQuery();
            while (rs.next()) {
                int count = rs.getInt("cnt");
                if (count > 0) {
                    return true;
                } else {
                    return false;
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                rs.close();
                ps.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        return false;
    }

    public Employee searchEmployee(String inputId) {
        Connection connection = JDBCUtils.getConnection();
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            String employeeSql = "select * from employee where employee_id = ?";
            ps = connection.prepareStatement(employeeSql);
            ps.setString(1, inputId);
            rs = ps.executeQuery();
            while (rs.next()) {
                Employee employeeReturn = new Employee();
                employeeReturn.setEmployee_id(rs.getString("employee_id"));
                employeeReturn.setEmployee_name(rs.getString("employee_name"));
                employeeReturn.setEmployee_email(rs.getString("employee_email"));
                employeeReturn.setBirthday(rs.getString("birthday"));
                employeeReturn.setAge(rs.getDouble("age"));
                employeeReturn.setJoin_date(rs.getString("join_date"));
                employeeReturn.setWork_experience(rs.getDouble("work_experience"));
                employeeReturn.setHire_date(rs.getString("hire_date"));
                employeeReturn.setCompany_experience(rs.getDouble("company_experience"));
                employeeReturn.setGender(rs.getString("gender"));
                employeeReturn.setDepartment_name(rs.getString("department_name"));
                employeeReturn.setState(rs.getString("state"));
                return employeeReturn;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                rs.close();
                ps.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        return null;
    }

    public boolean checkEmployeeEmail(String inputEmail) {
        Connection connection = JDBCUtils.getConnection();
        String employeeSql = "select count(*) as cnt from employee where employee_email = ?";
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            ps = connection.prepareStatement(employeeSql);
            ps.setString(1, inputEmail);
            rs = ps.executeQuery();
            while (rs.next()) {
                int count = rs.getInt("cnt");
                if (count > 0) {
                    return true;
                } else {
                    return false;
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                rs.close();
                ps.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        return false;
    }

    public void addEmployee(Employee employee) {
        Connection connection = JDBCUtils.getConnection();
        PreparedStatement ps = null;
        try {
            connection.setAutoCommit(false);
            String sqlInsert = "insert into employee " +
                    "(employee_id" +
                    ",employee_name" +
                    ",employee_email" +
                    ",birthday" +
                    ",join_date" +
                    ",hire_date" +
                    ",gender" +
                    ",department_name,state)" +
                    " values(?,?,?,?,?,?,?,?,?)";
            ps = connection.prepareStatement(sqlInsert);
            ps.setString(1, employee.getEmployee_id());
            ps.setString(2, employee.getEmployee_name());
            ps.setString(3, employee.getEmployee_email());
            ps.setString(4, employee.getBirthday());
            ps.setString(5, employee.getJoin_date());
            ps.setString(6, employee.getHire_date());
            ps.setString(7, employee.getGender());
            ps.setString(8, employee.getDepartment_name());
            ps.setString(9, STATE_ON);
            ps.executeUpdate();

            String departmentUpdate = "update department set employee_num = employee_num+1  " +
                    "where department_name = ? AND state = ?";
            ps = connection.prepareStatement(departmentUpdate);
            ps.setString(1, employee.getDepartment_name());
            ps.setString(2, De_STATE_ON);
            ps.executeUpdate();
            System.out.println("新增员工成功");
        } catch (SQLException e) {
            try {
                connection.rollback();
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
            throw new RuntimeException(e);
        } finally {
            try {
                ps.close();
                connection.commit();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public void deleteEmployee(String inputId) {
        Connection connection = JDBCUtils.getConnection();
        PreparedStatement ps = null;
        try {
            String sqlInsert = "update employee set state = ? where employee_id = ?";
            ps = connection.prepareStatement(sqlInsert);
            ps.setString(1, DELETE_ON);
            ps.setString(2, inputId);
            ps.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                ps.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public void updateEmployee(Employee employee) {
        Connection connection = JDBCUtils.getConnection();
        PreparedStatement ps = null;
        try {
            String sqlUpdate = "update employee set " +
                    " employee_name = ?" +
                    ",employee_email = ?" +
                    ",birthday = ?" +
                    ",join_date = ?" +
                    ",hire_date = ?" +
                    ",gender = ?" +
                    ",department_name = ?" +
                    " where employee_id = ?";
            ps = connection.prepareStatement(sqlUpdate);
            ps.setString(1, employee.getEmployee_name());
            ps.setString(2, employee.getEmployee_email());
            ps.setString(3, employee.getBirthday());
            ps.setString(4, employee.getJoin_date());
            ps.setString(5, employee.getHire_date());
            ps.setString(6, employee.getGender());
            ps.setString(7, employee.getDepartment_name());
            ps.setString(8, employee.getEmployee_id());
            ps.executeUpdate();
            System.out.println("修改员工成功");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                ps.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public void turnEmployee(Employee employee, String oldDepartmentId, String newDepartmentId, String today) {
        Connection connection = JDBCUtils.getConnection();
        PreparedStatement ps = null;
        try {
            connection.setAutoCommit(false);
            //新增履历表
            String sqlInsert = "insert into turn_department " +
                    "(user_id" +
                    ",over_date" +
                    ",new_department_id" +
                    ",old_department_id)" +
                    " values(?,?,?,?)";
            ps = connection.prepareStatement(sqlInsert);
            ps.setString(1, employee.getEmployee_id());
            ps.setString(2, today);
            ps.setString(3, newDepartmentId);
            ps.setString(4, oldDepartmentId);
            ps.executeUpdate();
            //更新员工部门名称
            String updateEmployeeSql = "update employee set department_name = ? where employee_id = ?";
            ps = connection.prepareStatement(updateEmployeeSql);
            ps.setString(1, employee.getDepartment_name());
            ps.setString(2, employee.getEmployee_id());
            ps.executeUpdate();
            //部门人数+1
            String updateNewDepartment = "update department set employee_num = employee_num + 1 " +
                    "where department_id = ?";
            ps = connection.prepareStatement(updateNewDepartment);
            ps.setString(1, newDepartmentId);
            ps.executeUpdate();

            //部门人数-1
            String updateOldDepartment = "update department set employee_num = employee_num - 1 " +
                    "where department_id = ?";
            ps = connection.prepareStatement(updateOldDepartment);
            ps.setString(1, oldDepartmentId);
            ps.executeUpdate();
        } catch (SQLException e) {
            try {
                connection.rollback();
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
            throw new RuntimeException(e);
        } finally {
            try {
                connection.commit();
                ps.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public Employee getEmployeeInJob(String inputDepartmentHeadId) {
        Connection connection = JDBCUtils.getConnection();
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            String employeeSql = "select * from employee where employee_id = ? AND state = ?";
            ps = connection.prepareStatement(employeeSql);
            ps.setString(1, inputDepartmentHeadId);
            ps.setString(2, STATE_ON);
            rs = ps.executeQuery();
            while (rs.next()) {
                Employee employeeReturn = new Employee();
                employeeReturn.setEmployee_id(rs.getString("employee_id"));
                employeeReturn.setEmployee_name(rs.getString("employee_name"));
                employeeReturn.setEmployee_email(rs.getString("employee_email"));
                employeeReturn.setBirthday(rs.getString("birthday"));
                employeeReturn.setAge(rs.getDouble("age"));
                employeeReturn.setJoin_date(rs.getString("join_date"));
                employeeReturn.setWork_experience(rs.getDouble("work_experience"));
                employeeReturn.setHire_date(rs.getString("hire_date"));
                employeeReturn.setCompany_experience(rs.getDouble("company_experience"));
                employeeReturn.setGender(rs.getString("gender"));
                employeeReturn.setDepartment_name(rs.getString("department_name"));
                employeeReturn.setState(rs.getString("state"));
                return employeeReturn;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                rs.close();
                ps.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        return null;
    }

    public List<Employee> checkEmployeeHeadDepartment() {
        Connection connection = JDBCUtils.getConnection();
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            String employeeSql = "SELECT" +
                    " employee.employee_id," +
                    " employee_name," +
                    " employee.gender," +
                    " employee.birthday," +
                    " employee.hire_date," +
                    " employee.department_name," +
                    " employee.state " +
                    "FROM" +
                    " employee" +
                    " LEFT JOIN account ON employee.employee_id = account.employee_id" +
                    " LEFT JOIN department ON employee.department_name = department.department_name " +
                    "WHERE" +
                    " department.department_name = (" +
                    " SELECT" +
                    " department.department_name " +
                    " FROM" +
                    " department" +
                    " LEFT JOIN employee ON employee.department_name = department.department_name" +
                    " LEFT JOIN account ON employee.employee_id = account.employee_id " +
                    " WHERE" +
                    " role = ? " +
                    " )";
            ps = connection.prepareStatement(employeeSql);
            ps.setString(1, "LEADER");
            rs = ps.executeQuery();
            List<Employee> employeeList = new ArrayList<>();
            while (rs.next()) {
                Employee employeeReturn = new Employee();
                employeeReturn.setEmployee_id(rs.getString("employee_id"));
                employeeReturn.setEmployee_name(rs.getString("employee_name"));
                employeeReturn.setGender(rs.getString("gender"));
                employeeReturn.setBirthday(rs.getString("birthday"));
                employeeReturn.setHire_date(rs.getString("hire_date"));
                employeeReturn.setDepartment_name(rs.getString("department_name"));
                employeeReturn.setState(rs.getString("state"));
                employeeList.add(employeeReturn);
            }
            return employeeList;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                rs.close();
                ps.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public Map<Employee,Map<String,String>> searchEmployeeMsg(String inputId) {
        Connection connection = JDBCUtils.getConnection();
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            String employeeSql = "SELECT" +
                    " employee.employee_id," +
                    " employee.employee_name," +
                    " employee.employee_email," +
                    " employee.gender," +
                    " employee.birthday," +
                    " employee.age," +
                    " employee.join_date," +
                    " employee.work_experience," +
                    " employee.hire_date," +
                    " employee.company_experience," +
                    " employee.department_name AS new_department_name," +
                    " department.department_name AS old_department_name," +
                    " turn_department.over_date," +
                    " turn_department.start_date " +
                    "FROM" +
                    " turn_department" +
                    " LEFT JOIN employee ON employee.employee_id = turn_department.user_id" +
                    " LEFT JOIN department ON turn_department.old_department_id = department.department_id " +
                    "WHERE" +
                    " employee_id = ?";
            ps = connection.prepareStatement(employeeSql);
            ps.setString(1, inputId);
            rs = ps.executeQuery();
            Map<String,String> turnMap = new LinkedHashMap<>();
            Map<Employee,Map<String,String>> resultMap = new LinkedHashMap<>();
            String newDepartment = "";
            int count = 0;
            Employee employeeReturn = new Employee();
            while (rs.next()) {
                employeeReturn.setEmployee_id(rs.getString("employee_id"));
                employeeReturn.setEmployee_name(rs.getString("employee_name"));
                employeeReturn.setEmployee_email(rs.getString("employee_email"));
                employeeReturn.setBirthday(rs.getString("birthday"));
                employeeReturn.setAge(rs.getDouble("age"));
                employeeReturn.setJoin_date(rs.getString("join_date"));
                employeeReturn.setWork_experience(rs.getDouble("work_experience"));
                employeeReturn.setHire_date(rs.getString("hire_date"));
                employeeReturn.setCompany_experience(rs.getDouble("company_experience"));
                employeeReturn.setGender(rs.getString("gender"));
                employeeReturn.setDepartment_name(rs.getString("new_department_name"));
                if(count == 0){
                    StringBuilder stringBuffer = new StringBuilder(rs.getString("over_date"));
                    newDepartment = rs.getString("new_department_name");
                    turnMap.put(stringBuffer.append("-").append("          ").toString()
                            ,newDepartment);
                }
                count++;
                StringBuilder stringBuffer = new StringBuilder(rs.getString("start_date"));
                turnMap.put(stringBuffer.append("-").append(rs.getString("over_date")).toString()
                        ,rs.getString("old_department_name"));
            }
            resultMap.put(employeeReturn,turnMap);
            return resultMap;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                rs.close();
                ps.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
